import Vue from 'vue'

Object.assign(Vue.prototype, {

  // 注入插槽
  // - @slot 插槽名
  // - @id 注入ID（相同ID的注入将被替换而非新增，但一前一后则可共存）
  // - @nodes 要注入的节点列表（null表示删除该注入）
  // - @before 是否加到最前面（否则加到最后面），替换时位置不变
  $injectSlot(slot, id, nodes, before = false) {
    const injection = { id, nodes }
    const f = this.$scopedSlots[slot]
    if (f && f.__origSlot) {
      const side = before ? f.__injectBefore : f.__injectAfter
      const index = side.findIndex(item => item.id === id)
      if (index < 0) {
        if (before) {
          side.unshift(injection)
        } else {
          side.push(injection)
        }
      } else {
        side[index] = injection
      }
    } else {
      const injected = props => {
        return [
          injected.__injectBefore.flatMap(item => item.nodes || []),
          injected.__origSlot && injected.__origSlot(props),
          injected.__injectAfter.flatMap(item => item.nodes || [])
        ].flat()
      }
      injected.__origSlot = f
      injected.__injectBefore = before ? [injection] : []
      injected.__injectAfter = before ? [] : [injection]
      this.$scopedSlots[slot] = injected
    }
  }
})
